package com.dreamlin.gankio.banner

import android.util.SparseArray
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.IdRes
import androidx.recyclerview.widget.RecyclerView
import coil.api.load
import com.dreamlin.gankio.R
import com.dreamlin.gankio.mvvm.home.feature.BannerModel
import com.youth.banner.adapter.BannerAdapter

class BannerImageAdapter(datas: List<BannerModel>) : BannerAdapter<BannerModel,
        BannerImageAdapter.BannerViewHolder>(datas), View.OnClickListener {

    constructor(datas: List<BannerModel>, listener: ImageClickListener) : this(datas) {
        this.imageClickListener = listener
    }

    var imageClickListener: ImageClickListener? = null

    override fun onCreateHolder(
        parent: ViewGroup?,
        viewType: Int
    ): BannerViewHolder {
        val inflate = LayoutInflater.from(parent!!.context)
            .inflate(R.layout.banner_layout, parent, false)
        val bannerViewHolder =
            BannerViewHolder(inflate)
        if (imageClickListener != null) {
            val ivBanner = bannerViewHolder.getView<ImageView>(R.id.ivBanner)
            ivBanner.setOnClickListener(this)
        }
        return bannerViewHolder
    }

    override fun onBindView(
        holder: BannerViewHolder?,
        data: BannerModel?,
        position: Int,
        size: Int
    ) {
        holder?.run {
            val ivBanner = getView<ImageView>(R.id.ivBanner)
            val tvTitle = getView<TextView>(R.id.tvTitle)
            ivBanner.tag = position
            data?.image?.let {
                ivBanner.load(it)
            }
            data?.title?.let {
                tvTitle.text = it
            }
        }
    }

    override fun onClick(v: View?) {
        if (v?.tag is Int) {
            val tag = v.tag as Int
            imageClickListener?.onClick(v as ImageView, mDatas[tag])
        }
    }

    class BannerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        private val views: SparseArray<View> = SparseArray()

        fun <V> getView(@IdRes id: Int): V {
            var view = views[id]
            view = view ?: itemView.findViewById(id)
            views.put(id, view)
            return view as V
        }

        init {

        }

    }

    interface ImageClickListener {
        fun onClick(imageView: ImageView, data: BannerModel)
    }

}